
#include "Connection.h"
#include <unistd.h>
#include <sys/syscall.h>
Connection::Connection(EventLoop *loop, std::unique_ptr<Socket> clientsock)
    : loop_(loop), clientsock_(std::move(clientsock)),disconnect_(false),clientchannel_(new Channel(loop_, clientsock_->fd()))
{
    printf("111111111111111111\n");
    //printf("clientsock->fd()::  %d\n",clientsock_->fd());
    //clientchannel_ = new Channel(loop_, clientsock_->fd());
     printf("22222222222222222\n");
    clientchannel_->setreadcallback(std::bind(&Connection::onmessage, this));
    clientchannel_->setclosecallback(std::bind(&Connection::closecallback, this));
    clientchannel_->seterrorcallback(std::bind(&Connection::errorcallback, this));
     printf("33333333333333333333\n");

    clientchannel_->setsendcallback(std::bind(&Connection::sendcallback, this));

    clientchannel_->enablereading();
    clientchannel_->useet(); // 设置边缘触发

    // printf(" hahaNew client connected: %s:%d\n", clientsock_->ip().c_str(), clientsock_->port());
}
Connection::~Connection()
{
    // delete clientsock_;
    // delete clientchannel_;
}
std::string Connection::ip()
{
    return clientsock_->ip();
}
uint16_t Connection::port()
{
    return clientsock_->port();
}

int Connection::fd() const
{
    return clientsock_->fd();
}

void Connection::closecallback()
{
    // printf("client(eventfd=%d) disconnected.\n", fd());
    // close(fd());
    disconnect_ = true;
    clientchannel_->remove();
    closecallback_(shared_from_this());
}
void Connection::errorcallback()
{
    // printf("else error\n");
    // close(fd());
    disconnect_ = true;
    clientchannel_->remove();
    errorcallback_(shared_from_this());
}

void Connection::setclosecallback(std::function<void(std::shared_ptr<Connection>)> f)
{
    closecallback_ = f;
}
void Connection::seterrorcallback(std::function<void(std::shared_ptr<Connection>)> f)
{
    errorcallback_ = f;
}

void Connection::sethaddlemsgcallback(std::function<void(std::shared_ptr<Connection>, std::string &)> f)
{
    haddlemsgcallback_ = f;
}

void Connection::onmessage()
{
    char buffer[1024];

    while (true)
    {                                   // 非阻塞IO循环读取
        bzero(&buffer, sizeof(buffer)); // 清空缓冲区

        ssize_t nread = read(fd(), buffer, sizeof(buffer));

        if (nread > 0)
        { // 成功读取数据
            printf("=========recv(eventfd=%d):%s\n", fd(), &buffer[4]);
            inputbuffer_.append(buffer, nread);

            // for (size_t i = 0; i < (size_t)nread; i++)
            // {
            //     buffer[i] = toupper(buffer[i]);
            // }

            // send(fd(), buffer, nread, 0); // 原样回发（使用nread而非strlen）
        }
        else if (nread == -1 && errno == EINTR)
        { // 被信号中断
            continue;
        }
        else if (nread == -1 && (errno == EAGAIN || errno == EWOULDBLOCK))
        { // 非阻塞无数据

            // outputbuffer_ = inputbuffer_;

            while (true)
            {
                int len = 0;

                memcpy(&len, inputbuffer_.data(), 4);
                if (inputbuffer_.size() < 4 + len)
                    break;

                std::string message(inputbuffer_.data() + 4, len);
                inputbuffer_.erase(0, 4 + len);

                haddlemsgcallback_(shared_from_this(), message);

                // message = "replay:"+message;
                // len = message.size();

                // std::string tmpbuf((char*)&len,4);
                // tmpbuf.append(message);

                // write(fd(),tmpbuf.data(),tmpbuf.size());
            }

            // 在这里调用数据处理函数
            // haddlemsgcallback_(this,message);
            //  暂时这样写
            //  write(fd(),outputbuffer_.data(),outputbuffer_.size());
            //  inputbuffer_.clear();
            //  outputbuffer_.clear();

            break;
        }
        else if (nread == 0)
        { // 客户端断开连接
            // printf("client(eventfd=%d) disconnected.\n", fd_);
            // close(fd_);
            // closecallback_();
            //clientchannel_->remove(); //从事件循环中删除channel
            closecallback();
            break;
        }
    }
}


void Connection::send(const char *data, int size)
{
    if(disconnect_){
        // printf("客户端连接已经断开,send()直接返回\n");
        return;
    }

    if(loop_->isinloopthread())
    {
        //IO线程，直接发送数据
        sendinloop(data,size);
    }
    else
    {//如果不是IO线程，把发送数据的操作交给IO线程执行
        // printf("******************Connection::send: %s\n",data);
        // loop_->queueinloop(std::bind(&Connection::sendinloop,this,data,size));
        // ⚠️ 在这里拷贝数据，避免 data 失效！

        // 脱了裤子放屁？ 
        auto sp = std::make_shared<std::string>(data, size);

        printf("******************Connection::send: %s\n", sp->c_str());

        // 使用 lambda 捕获 shared_ptr，保证数据在 sendinloop 前都有效
        loop_->queueinloop([this, sp]() {
            this->sendinloop(sp->data(), sp->size());
        });
        // sendinloop(data,size);
    }

}

void Connection::sendinloop(const char*data,int size )
{
   // outputbuffer_.append(data,size);
   printf("Connection::sendinloop:%s\n",data);
    outputbuffer_.appendwithhead(data, size);
    // 注册写事件
    clientchannel_->enablewriting();
}

void Connection::sendcallback()
{
    int write = ::write(fd(), outputbuffer_.data(), outputbuffer_.size()); // 尝试把outputbuffer中的数据全部发送出去
    // printf("haddlemessage thread is: %d\n", syscall(SYS_gettid));
    // fflush(stdout);
    if (write > 0)
    {
        outputbuffer_.erase(0, write);
    }

    if (outputbuffer_.size() == 0)
    {
        clientchannel_->disablewriting();
        sendcompletecallback_(shared_from_this());
    }

    
}

void Connection::setsendcompletecallback(std::function<void(std::shared_ptr<Connection>)> f)
{
    sendcompletecallback_ = f;
}